﻿using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Microsoft.Xna.Framework.Audio;
using Soundteller.Application.Facade.Contracts;
using Soundteller.Audio.Model;

namespace Soundteller.Application.Facade.Mappers
{
    public class SoundToXnaSoundConverter : ITypeConverter<Sound, XnaSound>
    {
        private static readonly object _lock = new object();

        public XnaSound Convert(ResolutionContext context)
        {
            var source = (Sound)context.SourceValue;

            return new XnaSound
            {
                Beat = source.Beat,
                Name = source.Name,
                SoundEffect = MapToSoundEffect(source)
            };
        }

        private SoundEffect MapToSoundEffect(Sound sound)
        {
            lock (_lock)
            {
                if (CacheManager.SoundEffects.Any(g => g.Name == sound.Name))
                    return CacheManager.SoundEffects.Single(g => g.Name == sound.Name);

                var soundEffect = GraphicsContext.Content.Load<SoundEffect>(sound.Name);
                CacheManager.SoundEffects.Add(soundEffect);

                return soundEffect;
            }
        }
    }
}
